﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace GZSolver
{
    class ThreadsSynchronizator
    {
        private int processesNum = 0;
        private ManualResetEvent threadBlocker = new ManualResetEvent(false);
        Dictionary<int, int> idSynchronizationList = new Dictionary<int, int>();

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="processNum">Number of threads in the execution pool</param>
        public ThreadsSynchronizator(int processNum)
        {
            this.processesNum = processNum;
        }

        /// <summary>
        /// Blocks all threads until processNum threads won't with id call this function
        /// </summary>
        /// <returns></returns>
        public void SynchronizeThreadsById(int id)
        {
            if (idSynchronizationList.ContainsKey(id))
            {
                idSynchronizationList[id]++;
                // Check if processesNum reached.
                if (idSynchronizationList[id] == processesNum)
                {
                    threadBlocker.Reset();
                    idSynchronizationList.Remove(id);
                    return;
                }
            }
            else
            {
                idSynchronizationList.Add(id, 1);
            }
            threadBlocker.WaitOne();
        }


    }
}
